package com.ai.zhly.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ai.dmc.index.base.impl.base.BaseServiceImpl;
import com.ai.dmc.index.common.InitParam;
import com.ai.dmc.index.common.bean.CommonBaseBean;
import com.ai.dmc.index.common.util.DateUtil;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
* @Title: HotMapServiceImpl.java
* @Description:热力图service
* @author xueyf3  
* @date 2016年5月23日 下午4:22:54
* Copyright：Copyright (c) 2016
* Company：北京亚信智慧数据科技有限公司
* @version V1.0
 */
public class HotMapUtilServiceImpl extends BaseServiceImpl implements IHotMapUtilService{
	// 定义对应Mapper文件的命名空间
    private static final String NAMESPACE = "HotMap.";
    
    public static Logger log = LoggerFactory.getServiceLog(HotMapUtilServiceImpl.class);

	/**
	 * 
	 * @Description : 热力图数据处理-实时
	 * @return
	 * @return JSONObject
	 * 
	 * @author : wucm
	 * @date : 2015年7月24日 上午9:26:11
	 * 
	 */
	@Override
	public JSONObject dealHotMapData0(List<JSONObject> rList) {
		JSONObject j = new JSONObject();

		int maxNum = 0;
		int curNum = 0;
		// 数据处理
		Map<String, JSONArray> hMap = new HashMap<String, JSONArray>();
		for (JSONObject json : rList) {
			String date = json.getString("datetime_id");
			JSONArray arr = hMap.get(date);
			if (null == arr) {
				arr = new JSONArray();
			}
			json.remove("datetime_id");
			arr.add(json);
			hMap.put(date, arr); // date不是应该一致么？同一天的，还是存在跨天？

			curNum = json.getInt("count");
			if (curNum > maxNum) {
				maxNum = curNum;
			}
		}

		// 将数据组织成json
		for (String key : hMap.keySet()) {
			j.put(key, hMap.get(key));
			j.put("time", key);
			j.put("max", maxNum);
		}

		return j;
	}

	/**
	 * 
	 * @Description : 热力图数据处理--昨天或者前天
	 * @return
	 * @return JSONObject
	 * 
	 * @author : wucm
	 * @date : 2015年7月24日 上午9:26:11
	 * 
	 */
	@Override
	public JSONObject dealHotMapData24Or48(List<JSONObject> rList) {
		JSONObject j = new JSONObject();

		// 数据处理
		int maxNum = 0;
		int curNum = 0;

		Map<String, JSONArray> hMap = new HashMap<String, JSONArray>();
		for (JSONObject json : rList) {
			String date = json.getString("datetime_id");
			JSONArray arr = hMap.get(date);
			if (null == arr) {
				arr = new JSONArray();
			}
			json.remove("datetime_id");
			arr.add(json);
			hMap.put(date, arr);

			curNum = json.getInt("count");
			if (curNum > maxNum) {
				maxNum = curNum;
			}
		}

		// 将数据组织成json
		for (String key : hMap.keySet()) {
			j.put(key, hMap.get(key));
		}

		j.put("max", maxNum);

		return j;
	}

	/**
	 * 根据区域获取热力图最大值
	 * 
	 * @param areaId
	 * @return
	 * @throws Exception
	 */
	@Override
	public String getHotMapMaxByAreaId(String areaId) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		params.put("areaId", areaId);
		if (areaId.length() == InitParam.AREA_CITY_LENGTH) {
			params.put("areaFlag", "city");
		} else if (areaId.length() == InitParam.AREA_COUNTY_LENGTH) {
			params.put("areaFlag", "county");
		} else if (areaId.length() == InitParam.AREA_REGION_LENGTH) {
			params.put("areaFlag", "region");
		}
		// 查询数据
		String max = this.getBaseDao().queryForObject(
                NAMESPACE + "getHotMapMax",params,String.class);
		return max;
	}

	/**
	 * 
	 * @Description : 查询热力图-实时
	 * @param regionId
	 * @return
	 * @return JSONArray
	 * 
	 * @author : wucm
	 * @date : 2015年7月7日 下午4:17:41
	 * 
	 */
	@Override
	public List<JSONObject> queryHotMap0Data(String regionId) {
		// 查询数据
		List<JSONObject> jList = new ArrayList<JSONObject>();
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("regionId", regionId);
		if (regionId.equals(InitParam.DEPLOY_PROVINCE_ID)) {
			// 全省
			paramMap.put("regionIdField", "1");
			paramMap.put("regionId", "1");
			paramMap.put("tableName", "st_tour_prov_chart_min");
		} else if (regionId.length() == InitParam.AREA_CITY_LENGTH) {
			// 地市
			paramMap.put("regionIdField", "city_id");
			paramMap.put("tableName", "st_tour_city_chart_min");
		} else if (regionId.length() == InitParam.AREA_REGION_LENGTH) {
			// 区域
			paramMap.put("regionIdField", "region_id");
			paramMap.put("tableName", "st_tour_region_chart_min");
		}
		List<CommonBaseBean> cList = this.getBaseDao().queryForList(
                NAMESPACE + "queryHotMap0",paramMap,CommonBaseBean.class);
		if (null == cList || cList.size() == 0) {
			cList = new ArrayList<CommonBaseBean>();
		}
		// 拼接json
		for (CommonBaseBean bean : cList) {
			JSONObject j = new JSONObject();
			SimpleDateFormat sdf4return = new SimpleDateFormat(
					"yyyyMMddHHmm");
			SimpleDateFormat sdf4return2 = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm");
			String datetime_id = "";
			try {
				datetime_id = sdf4return2
						.format(sdf4return.parse(bean.getQuery_value1()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			String lng = bean.getQuery_value2();
			String lat = bean.getQuery_value3();
			String count = bean.getQuery_value4();
			int countNum = 0;
			if (count!=null && count.matches("[0-9]+")) {
				countNum = Integer.valueOf(count);
			}
			j.put("datetime_id", datetime_id);
			j.put("lng", lng);
			j.put("lat", lat);
			j.put("count", countNum);

			jList.add(j);
		}
		return jList;
	}


	/**
	 * 
	 * @Description : 查询热力图-昨天
	 * @param regionId
	 * @return
	 * @return JSONArray
	 * 
	 * @author : wucm
	 * @date : 2015年7月7日 下午4:17:41
	 * 
	 */
	@Override
	public List<JSONObject> queryHotMap24Data(String regionId) {
		
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("regionId", regionId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(date);
		rightNow.add(Calendar.HOUR, -1);// 时间-1小时
		date = rightNow.getTime();
		String endTime = sdf.format(date) + "01";// 结束时间过1分
		String endDate = sdf2.format(date);

		rightNow.add(Calendar.DAY_OF_YEAR, -1);// 日期-1天
		date = rightNow.getTime();
		String startTime = sdf.format(date) + "00";
		String startDate = sdf2.format(date);

		paramMap.put("endTime", endTime);
		paramMap.put("startTime", startTime);

		paramMap.put("endDate", endDate);
		paramMap.put("startDate", startDate);
		if (regionId.equals(InitParam.DEPLOY_PROVINCE_ID)) {
			// 全省
			paramMap.put("regionIdField", "1");
			paramMap.put("regionId", "1");
			paramMap.put("tableName", "st_tour_prov_chart_min");
		} else if (regionId.length() == InitParam.AREA_CITY_LENGTH) {
			// 地市
			paramMap.put("regionIdField", "city_id");
			paramMap.put("tableName", "st_tour_city_chart_min");
		} else if (regionId.length() == InitParam.AREA_REGION_LENGTH) {
			// 区域
			paramMap.put("regionIdField", "region_id");
			paramMap.put("tableName", "st_tour_region_chart_min");
		}

		List<JSONObject> jList = new ArrayList<JSONObject>();
		List<CommonBaseBean> cList = this.getBaseDao().queryForList(
                NAMESPACE + "queryHotMap24",paramMap,CommonBaseBean.class);
		if (null == cList || cList.size() == 0) {
			cList = new ArrayList<CommonBaseBean>();
		}

		// 拼接json
		for (CommonBaseBean bean : cList) {
			JSONObject j = new JSONObject();
			SimpleDateFormat sdf4return = new SimpleDateFormat(
					"yyyyMMddHHmm");
			SimpleDateFormat sdf4return2 = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm");
			String datetime_id = "";
			try {
				datetime_id = sdf4return2
						.format(sdf4return.parse(bean.getQuery_value1()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String lng = bean.getQuery_value2();
			String lat = bean.getQuery_value3();
			String count = bean.getQuery_value4();
			int countNum = 0;
			if (count!=null && count.matches("[0-9]+")) {
				countNum = Integer.valueOf(count);
			}
			j.put("datetime_id", datetime_id);
			j.put("lng", lng);
			j.put("lat", lat);
			j.put("count", countNum);

			jList.add(j);
		}

		return jList;
	}
	
	/**
	 * 
	 * @Description : 查询热力图-前天
	 * @param regionId
	 * @return
	 * @return JSONArray
	 * 
	 * @author : wucm
	 * @date : 2015年7月7日 下午4:17:41
	 * 
	 */
	@Override
	public List<JSONObject> queryHotMap48Data(String regionId) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("regionId", regionId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(date);
		rightNow.add(Calendar.HOUR, -1);// 时间-1小时
		rightNow.add(Calendar.DAY_OF_YEAR, -1);// 日期-1天,昨天
		date = rightNow.getTime();
		String endTime = sdf.format(date) + "01";// 昨天时间点
		String endDate = sdf2.format(date); // 昨天日期

		// rightNow.add(Calendar.DAY_OF_YEAR,-1);//日期-1天,昨天
		// date=rightNow.getTime();
		// String midDate = sdf2.format(date); //昨天日期

		rightNow.add(Calendar.DAY_OF_YEAR, -1);// 日期-1天，前天
		date = rightNow.getTime();
		String startTime = sdf.format(date) + "00";// 前天时间点
		String startDate = sdf2.format(date);// 前天日期
		paramMap.put("endTime", endTime);
		paramMap.put("startTime", startTime);

		paramMap.put("endDate", endDate);
		paramMap.put("startDate", startDate);

		if (regionId.equals(InitParam.DEPLOY_PROVINCE_ID)) {
			// 全省
			paramMap.put("regionIdField", "1");
			paramMap.put("regionId", "1");
			paramMap.put("tableName", "st_tour_prov_chart_min");
		} else if (regionId.length() == InitParam.AREA_CITY_LENGTH) {
			// 地市
			paramMap.put("regionIdField", "city_id");
			paramMap.put("tableName", "st_tour_city_chart_min");
		} else if (regionId.length() == InitParam.AREA_REGION_LENGTH) {
			// 区域
			paramMap.put("regionIdField", "region_id");
			paramMap.put("tableName", "st_tour_region_chart_min");
		}

		List<JSONObject> jList = new ArrayList<JSONObject>();
		List<CommonBaseBean> cList =this.getBaseDao().queryForList(
                NAMESPACE + "queryHotMap48",paramMap,CommonBaseBean.class);

		if (null == cList || cList.size() == 0) {
			cList = new ArrayList<CommonBaseBean>();
		}

		// 拼接json
		for (CommonBaseBean bean : cList) {
			JSONObject j = new JSONObject();
			SimpleDateFormat sdf4return = new SimpleDateFormat(
					"yyyyMMddHHmm");
			SimpleDateFormat sdf4return2 = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm");
			String datetime_id = "";
			try {
				datetime_id = sdf4return2
						.format(sdf4return.parse(bean.getQuery_value1()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String lng = bean.getQuery_value2();
			String lat = bean.getQuery_value3();
			String count = bean.getQuery_value4();
			int countNum = 0;
			if (count!=null && count.matches("[0-9]+")) {
				countNum = Integer.valueOf(count);
			}
			j.put("datetime_id", datetime_id);
			j.put("lng", lng);
			j.put("lat", lat);
			j.put("count", countNum);

			jList.add(j);
		}

		return jList;
	}

	/**
	 * 
	 * @Description : 查询热力图-昨天和前天
	 * @param regionId
	 * @return
	 * @return JSONArray
	 * 
	 * @author : wucm
	 * @date : 2015年7月7日 下午4:17:41
	 * 
	 */
	@Override
	public JSONObject queryHotMap24And48(String regionId) {
		JSONObject j = new JSONObject();

		// 查询数据
		List<JSONObject> rList24 = null;
		List<JSONObject> rList48 = null;
		JSONObject compareDate = null;
		rList24 = this.queryHotMap24Data(regionId);
		rList48 = this.queryHotMap48Data(regionId);
		compareDate = this.queryCompareDate(regionId);

		JSONObject j24 = dealHotMapData24Or48(rList24);
		JSONObject j48 = dealHotMapData24Or48(rList48);

		String today = compareDate.getString("today");
		String yesterday = compareDate.getString("yesterday");
		String lastday = compareDate.getString("lastday");

		j.put("map24", j24);
		j.put("map48", j48);
		j.put("today", today);
		j.put("yesterday", yesterday);
		j.put("lastday", lastday);

		// 存在2个最大值--24小时内和48小时内，是共用一个还是分2个最大值？
		int map24Max = j24.getInt("max");
//		int map48Max = j48.getInt("max");

		/*if (map24Max > map48Max) {
			j.put("max", map24Max);
		} else {
			j.put("max", map48Max);
		}*/
		
		//为了客户满意，采用24小时的最大值为统一标准
		//否则回放和对比模式，热力图形不一致
		j.put("max", map24Max);
		
		return j;
	}
	
	/**
	 * 
	 * @Description :获取热力图对比日期
	 * @author xueyf3
	 * @date 创建时间：2015年7月17日 下午5:27:49
	 * @version 1.0
	 */
	@Override
	public JSONObject queryCompareDate(String regionId) {
		JSONObject j = new JSONObject();
		Map<String, String> paramMap = new HashMap<String, String>();
		if (regionId.equals(InitParam.DEPLOY_PROVINCE_ID)) {
			// 全省
			paramMap.put("tableName", "st_tour_prov_chart_min");
		} else if (regionId.length() == InitParam.AREA_CITY_LENGTH) {
			// 地市
			paramMap.put("tableName", "st_tour_city_chart_min");
		} else if (regionId.length() == InitParam.AREA_REGION_LENGTH) {
			// 区域
			paramMap.put("tableName", "st_tour_region_chart_min");
		}

		// 查询数据
		List<CommonBaseBean> cList = this.getBaseDao().queryForList(
                NAMESPACE + "queryCompareDate",paramMap,CommonBaseBean.class);

		if (null == cList || cList.size() == 0) {
			cList = new ArrayList<CommonBaseBean>();
		}

		// 拼接json
		if (cList.size() > 0) {
			CommonBaseBean bean = cList.get(0);
			DateUtil d = DateUtil.getInstance();
			String today = bean.getQuery_value1();
			String yesterday = d.getXDay(today, "yyyyMMddhhmm", -1);
			String lastday = d.getXDay(today, "yyyyMMddhhmm", -2);

			j.put("today", today.substring(0, 4) + "-"
					+ today.substring(4, 6) + "-" + today.substring(6, 8));
			j.put("yesterday",
					yesterday.substring(0, 4) + "-"
							+ yesterday.substring(4, 6) + "-"
							+ yesterday.substring(6, 8));
			j.put("lastday",
					lastday.substring(0, 4) + "-" + lastday.substring(4, 6)
							+ "-" + lastday.substring(6, 8));
		}

		return j;
	}


	/**
	 * 
	 * @Description : 查询热力图-实时
	 * @param regionId
	 * @return
	 * @return JSONArray
	 * 
	 * @author : wucm
	 * @date : 2015年7月7日 下午4:17:41
	 * 
	 */
	@Override
	public JSONObject queryHotMap0(String regionId) {
		// 查询数据
		List<JSONObject> rList = null;
		rList = this.queryHotMap0Data(regionId);
		// 热力图数据处理
		JSONObject j = dealHotMapData0(rList);

		return j;
	}

	/**
	 * 
	 * @Description : 查询热力图-昨天
	 * @param regionId
	 * @return
	 * @return JSONArray
	 * 
	 * @author : wucm
	 * @date : 2015年7月7日 下午4:17:41
	 * 
	 */
	@Override
	public JSONObject queryHotMap24(String regionId) {
		// 查询数据
		List<JSONObject> rList = null;
		rList = this.queryHotMap24Data(regionId);
		// 热力图数据处理
		JSONObject j = dealHotMapData24Or48(rList);

		return j;
	}

	/**
	 * 
	 * @Description : 查询热力图-前天
	 * @param regionId
	 * @return
	 * @return JSONArray
	 * 
	 * @author : wucm
	 * @date : 2015年7月7日 下午4:17:41
	 * 
	 */
	@Override
	public JSONObject queryHotMap48(String regionId) {
		// 查询数据
		List<JSONObject> rList = null;
		rList = this.queryHotMap48Data(regionId);
		// 热力图数据处理
		JSONObject j = dealHotMapData24Or48(rList);

		return j;
	}


	



}
